import {
  FlatList,
  Image, NativeScrollEvent, NativeSyntheticEvent,
  RefreshControl,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View
} from "react-native";
import { CommonConfig, initMeta, windowHeight } from "../util";
import { useCallback, useEffect, useRef, useState } from "react";
import RowTab from "../components/RowTab";
import { ArticleType, DictType, MetaType } from "../util/publicType";
import { useFocusEffect } from "@react-navigation/native";
import { articleDict, articleList } from "../api";
import ArticleList from "../components/ArticleList";
import Empty from "../components/Empty";
import Loading from "../components/Loading";
import { ActivityIndicator } from "@ant-design/react-native";
import { get } from "react-native/Libraries/TurboModule/TurboModuleRegistry";

const Article = () => {
  // 搜索名字
  const [name, setName] = useState<string>("");
  // tab数据
  const [tabData, setTabDats] = useState<Array<DictType>>([]);
  //数据
  const [data, setData] = useState<Array<ArticleType>>([]);
  // 是否下拉
  const [refreshing, setRefreshing] = useState(false);
  // 请求id
  const [id, setId] = useState<string>("");
  // 请求加载
  const [isLoading, setIsLoding] = useState<boolean>(true);
  // 分页数据
  const [meta, setMeta] = useState<MetaType>(initMeta);
  // 请求页
  const [page, setPage] = useState<number>(1);
  // 滚动组件
  const scEle = useRef<ScrollView | null>(null);

  // 下拉触发
  const onRefresh = useCallback(() => {
    if (!refreshing) {
      setRefreshing(true);
      getData(id, true);
    }
  }, [id]);

  useEffect(() => {
    articleDict().then(r => {
      setTabDats(r.data);
      setRefreshing(false);
      setId(r.data[0].id);
      getData(r.data[0].id);
    });
  }, []);


  // tab切換时
  const tabChange = (v: number) => {
    setId(tabData[v].id);
    setPage(1);
    getData(tabData[v].id, true);
  };

  // 文章列表
  const getData = (id: string, isClear: Boolean = false) => {
    setIsLoding(true);
    articleList(id, page, name).then(r => {
      if (isClear) {
        setData(r.data);
      } else {
        setData(v => {
          return [...v, ...r.data];
        });
      }
      setRefreshing(false);
      setIsLoding(false);
      setMeta(r.meta);
    });
  };

  const scrollEnd = (e: NativeSyntheticEvent<NativeScrollEvent>) => {
    // 滑动距离
    const scrollY: number = e.nativeEvent.contentOffset.y;
    // 盒子本身高度
    const scrollHeight: number = e.nativeEvent.layoutMeasurement.height;
    // 盒子内容高度
    const contentHeight: number = e.nativeEvent.contentSize.height;
    console.log("是否触发");
    console.log(page);
    console.log(meta.lastPage);
    // 触发上拉，内容占有的高度已经小于等于scrollview与滚动的高度值，肯定触底
    if (scrollHeight + scrollY >= contentHeight) {
      if (page >= meta.lastPage) {
        return;
      } else {
        setPage(v => v++);
        getData(id);
      }
    }
  };
  return (
    <View style={styles.box}>
      {/*搜索*/}
      <View style={styles.header}>
        <View style={styles.headerLeft}>
          <Image style={{ width: 20, height: 20 }} source={require("../static/search.png")}></Image>
          <TextInput style={{ flex: 1, padding: 6, color: "#111", height: 30 }} placeholder="请输入文章名称"
                     defaultValue={name} onChangeText={v => setName(v)}></TextInput>
          <TouchableOpacity onPress={() => setName("")} style={styles.headerClose}>
            <Image style={{ width: 8, height: 8 }} source={require("../static/close.png")}></Image>
          </TouchableOpacity>
        </View>
        <TouchableOpacity onPress={() => console.log("开始搜索")}>
          <Text style={styles.headerText}>搜索</Text>
        </TouchableOpacity>
      </View>
      {/*tabs*/}
      <RowTab data={tabData} tabChange={(v) => tabChange(v)} />
      {/* 列表 */}
      <ScrollView
        ref={scEle}
        overScrollMode="auto"
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}
        showsVerticalScrollIndicator={false}
        alwaysBounceHorizontal={false}
        onMomentumScrollEnd={scrollEnd}
        bounces={true}
        contentContainerStyle={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          flexDirection: "row",
          flexWrap: "wrap"
        }}>
        {
          data.length > 0 ? data.map(v => {
            return (
              <ArticleList key={v.id} item={v} />
            );
          }) : <Empty isText={true} />
        }
        <Loading isLoading={isLoading} />
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  box: {
    width: "100%",
    height: windowHeight,
    paddingTop: 10,
    paddingBottom: 10,
    display: "flex"
  },
  header: {
    width: "100%",
    display: "flex",
    alignItems: "center",
    flexDirection: "row",
    justifyContent: "space-between",
    paddingLeft: 10,
    paddingRight: 10
  },
  headerLeft: {
    width: "90%",
    borderRadius: 30,
    fontSize: 12,
    padding: 10,
    backgroundColor: "#fff",
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    height: 40
  },
  header_input: {
    flex: 1
  },
  headerClose: {
    width: 16,
    height: 16,
    borderRadius: 15,
    backgroundColor: "#aaa",
    display: "flex",
    alignItems: "center",
    justifyContent: "center"
  },
  headerText: {
    color: CommonConfig.fontColor,
    fontSize: 14
  }
});

export default Article;
